package cn.zcy.springboot_web.config;

import cn.zcy.springboot_web.interceptors.TimeInterceptors;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;

@Configuration
//@EnableWebMvc   //添加此注解会是springboot自动配置mvc配置失效
public class MyWebMvcConfiguration implements WebMvcConfigurer {

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {

        configurer.setUseTrailingSlashMatch(false);

    }

    /**
     * 添加拦截器
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new TimeInterceptors())  //添加拦截器
                .addPathPatterns("/**");  //拦截的映射规则
//        .excludePathPatterns("")// 排除拦截的映射规则
        // 添加国际化拦截器
        registry.addInterceptor(new LocaleChangeInterceptor())
                .addPathPatterns("/**");//拦截映射规则
    }

    /**
     * 添加跨域请求的映射
     *
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/user/**") //映射服务器中哪些http接口允许跨域访问
                .allowedOrigins("http://localhost:8081/") //配置哪些来源有权限进行跨域
                .allowedMethods("GET", "POST", "DElETE", "PUT")//配置运行跨域访问的请求方法
        ;
    }

    /**
     * 添加视图控制器 ，立即访问
     *
     * @param registry
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/tuling").setViewName("hello");

    }

    @Bean
    public LocaleResolver localeResolver(){
        CookieLocaleResolver cookieLocaleResolver=new CookieLocaleResolver();
        //设置过期时间
        cookieLocaleResolver.setCookieMaxAge(60*60*24*30);
        cookieLocaleResolver.setCookieName("local");
        return cookieLocaleResolver;
    }
}
